<?php
    /*
    * Copyright (c) 2007, Osuvaldo Ramos
    * 
    * All rights reserved.
    * 
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions are
    * met:
    *
    *    * Redistributions of source code must retain the above copyright
    *      notice, this list of conditions and the following disclaimer.
    *    * Redistributions in binary form must reproduce the above copyright
    *      notice, this list of conditions and the following disclaimer in the
    *      documentation and/or other materials provided with the distribution.
    *    * Neither the name of the CoreTech nor the names of its
    *      contributors may be used to endorse or promote products derived from
    *      this software without specific prior written permission.
    * 
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
    * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    * 
    * $Id: PrivateMessages.php 2 2008-01-21 02:48:28Z xdracox $
    */
    
    if ( !defined('BNETCS') || !defined('ROOT') ) exit();
    
    class PrivateMessages
    {
        function PrivateMessages()
        {
            $this->smarty = new Smarty();
            $this->smarty->template_dir = ROOT.'/mods/PrivateMessages';
            $this->smarty->compile_dir = ROOT.'/mods/PrivateMessages';
        }
        
        function onLogin()
        {
        }
        
        function displayConsole()
        {
            $msgs = $this->getNewMessages();
            $inbox = sizeof($msgs);
            
            $actions = array();
            
            $actions[] = array
            (
                'text' => 'Inbox ('.$inbox.')',
                'addr' => 'console.php?a=m&amp;m=PrivateMessages&amp;p=in'
            );
            
            $actions[] = array
            (
                'text' => 'Send Message',
                'addr' => 'console.php?a=m&amp;m=PrivateMessages&amp;p=sm'
            );
            
            $this->smarty->assign('actions', $actions);
            
            $this->smarty->display('console.tpl');
        }
        
        function getNewMessages()
        {
            global $mdb2, $auth;
            
            $msgs = array();
            
            $sql = sprintf('SELECT *
                FROM bnetcs_messages
                WHERE pm_status = "unread"
                    AND pm_recipient_id = %d', $auth->getAuthData('member_id'));
            $result = $mdb2->query($sql);
            
            if ( PEAR::isError($result) )
            {
                $msg = 'MySQL query failed: '.$result->getMessage();
                trigger_error($msg, E_USER_ERROR);
            }
            else
            {
                while ( $row = $result->fetchRow() )
                {
                    $sql = sprintf('SELECT member_login
                        FROM bnetcs_members
                        WHERE member_id = %d', $row['pm_sender_id']);
                    $sender_result = $mdb2->query($sql);
                    
                    if ( PEAR::isError($sender_result) )
                    {
                        $msg = 'MySQL query failed: '
                            .$sender_result->getMessage();
                        trigger_error($msg, E_USER_ERROR);
                    }
                    
                    $sender_row = $sender_result->fetchRow();
                    $sender_name = $sender_row['member_login'];
                    
                    $msgs[] = array
                    (
                        'id' => $row['pm_id'],
                        'sender' => $sender_name,
                        'time_sent' => $row['pm_time_sent'],
                        'subject' => $row['pm_subject'],
                        'body' => $row['pm_body']
                    );
                }
            }
            
            return $msgs;
        }
        
        function displayPage($page)
        {
            global $mdb2, $auth;
            
            switch ( $page )
            {
                case 'sm':
                {
                    if ( isset($_POST['subject']) && isset($_POST['body'])
                        && isset($_POST['recipient']) )
                    {
                        $subject = htmlentities($_POST['subject']);
                        $body = $_POST['body'];
                        $body = strip_tags($body, '<b><i><u><li><ol><ul><br>');
                        $body = nl2br($body);
                        $recipient = intval($_POST['recipient']);
                        
                        $sql = sprintf('INSERT
                            INTO bnetcs_messages (pm_sender_id, pm_recipient_id,
                                pm_subject, pm_body, pm_time_sent)
                            VALUES (%d, %d, "%s", "%s", %d)',
                            $auth->getAuthData('member_id'), $recipient,
                            $subject, $body, time());
                        $result = $mdb2->query($sql);
                        
                        if ( PEAR::isError($result) )
                        {
                            $msg = 'MySQL query failed: '.$result->getMessage();
                            trigger_error($msg, E_USER_ERROR);
                        }
                        else
                        {
                            $msg = 'Message sent successfully.';
                            $_SESSION['notices'] = array($msg);
                            header('Location: console.php');
                        }
                    }
                    else
                    {
                        $members = array();
                        
                        $sql = 'SELECT *
                            FROM bnetcs_members';
                        $result = $mdb2->query($sql);
                        
                        if ( PEAR::isError($result) )
                        {
                            $msg = 'MySQL query failed: '.$result->getMessage();
                            trigger_error($msg, E_USER_ERROR);
                        }
                        else
                        {
                            while ( $row = $result->fetchRow() )
                            {
                                $members[] = array
                                (
                                    'id' => $row['member_id'],
                                    'name' => $row['member_login']
                                );
                            }
                            
                            $this->smarty->assign('members', $members);
                            
                            display_header();
                            $this->smarty->display('sendmessage.tpl');
                            display_footer();
                        }
                    }
                    
                    break;
                }
                case 'in':
                {
                    if ( isset($_GET['pm']) )
                    {
                        $msg_id = intval($_GET['pm']);
                        
                        $sql = sprintf('SELECT *
                            FROM bnetcs_messages
                            WHERE pm_id = %d', $msg_id);
                        $result = $mdb2->query($sql);
                        
                        if ( PEAR::isError($result) )
                        {
                            $msg = 'MySQL query failed: '.$result->getMessage();
                            trigger_error($msg, E_USER_ERROR);
                        }
                        
                        $row = $result->fetchRow();
                        
                        $mid = $auth->getAuthData('member_id');
                        
                        if ( $row['pm_recipient_id'] != $mid )
                        {
                            $msg = 'That is not your message!';
                            $_SESSION['errors'] = array($msg);
                            header('Location: console.php');
                            return;
                        }
                        
                        $this->smarty->assign('id', $row['pm_id']);
                        $this->smarty->assign('subject', $row['pm_subject']);
                        $this->smarty->assign('body', $row['pm_body']);
                        
                        $sql = sprintf('SELECT member_login
                            FROM bnetcs_members
                            WHERE member_id = %d', $row['pm_sender_id']);
                        $result = $mdb2->query($sql);
                        
                        if ( PEAR::isError($result) )
                        {
                            $msg = 'MySQL query failed: '.$result->getMessage();
                            trigger_error($msg, E_USER_ERROR);
                        }
                        
                        $row = $result->fetchRow();
                        
                        $this->smarty->assign('sender', $row['member_login']);
                        
                        display_header();
                        $this->smarty->display('message.tpl');
                        display_footer();
                    }
                    else
                    {
                        $msgs = $this->getNewMessages();
                        
                        $this->smarty->assign('msgs', $msgs);
                        
                        display_header();
                        $this->smarty->display('inbox.tpl');
                        display_footer();
                    }
                    
                    break;
                }
            }
        }
    }
?>
